package top.roadvast.arith;

import org.junit.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @Author 郭泽鹏
 * @Date 2022/1/13 9:18
 * @Version 1.0
 * @Description
 */
public class BigDecimalDemo {
    private static BigDecimal num1 = null;
    private static BigDecimal num2 = null;

    /**
     * 加法
     */
    @Test
    public void testAdd() {
        num1 = new BigDecimal("88.88");
        num2 = new BigDecimal("11.12");
        final BigDecimal add = num1.add(num2);
        System.out.println("num1 add num2 = " + add);
    }

    /**
     * 减法
     */
    @Test
    public void testSub() {
        num1 = new BigDecimal("88.88");
        num2 = new BigDecimal("11.12");
        final BigDecimal subtract = num1.subtract(num2);
        System.out.println("num1 subtract num2 = " + subtract);
    }

    /**
     * 乘法
     */
    @Test
    public void testMulti() {
        num1 = new BigDecimal("88.88");
        num2 = new BigDecimal("11.12");
        final BigDecimal multiply = num1.multiply(num2);
        System.out.println("num1 multi num2 = " + multiply);
    }

    /**
     * 除法
     * 如果没有四舍五入，除不尽的时候就会报错：java.lang.ArithmeticException
     */
    @Test
    public void testDivide01() {
        num1 = new BigDecimal("88.88");
        num2 = new BigDecimal("11.12");
        final BigDecimal divide = num1.divide(num2);
        System.out.println(divide);
    }

    /**
     * 除法：保留小数
     */
    @Test
    public void testDivide02() {
        num1 = new BigDecimal("88.88");
        num2 = new BigDecimal("11.12");
        final BigDecimal divide = num1.divide(num2, 2, RoundingMode.HALF_UP);
        System.out.println("num1 divide num2 = " + divide);
    }

    /**
     * 比较大小
     */
    @Test
    public void testCompare() {
        BigDecimal number1 = new BigDecimal("88.88");
        BigDecimal number2 = new BigDecimal("11.11");
        BigDecimal number3 = new BigDecimal("99.99");
        BigDecimal number4 = new BigDecimal("88.88");

        System.out.println("number1 compareTo number2 = " + number1.compareTo(number2));
        System.out.println("number1 compareTo number3 = " + number1.compareTo(number3));
        System.out.println("number1 compareTo number4 = " + number1.compareTo(number4));
    }

    /**
     * 常量
     */
    @Test
    public void testConstant() {
        System.out.println(BigDecimal.ZERO);
        System.out.println(BigDecimal.ONE);
    }

    /**
     * double类型
     */
    @Test
    public void testDouble() {
        BigDecimal num1 = new BigDecimal(0.01);     //不使用double类型的参数，toString的时候结果会出错
        System.out.println(num1.toString());    //0.01000000000000000020816681711721685132943093776702880859375

        BigDecimal num2 = BigDecimal.valueOf(0.01);
        System.out.println(num2.toString());    //0.01
    }

}
